package com.asiainfo.iam.tool;

import com.asiainfo.iam.controller.DMDatabaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;


/**
 * 线程本地存储数据库连接
 */
@Component
public class ConnectThreadLocal {
    @Autowired
    private DMDatabaseController dmDatabaseController;

    // 使用ThreadLocal确保线程安全
    private final ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    /**
     * 创建数据库连接并存储到ThreadLocal
     */
    public Connection createConnection(String host, String port, String user, String password) throws SQLException {
        // 实际项目中应使用连接池
        Connection connection = dmDatabaseController.createConn(host, port, user, password);
        connectionThreadLocal.set(connection);
        return connection;
    }

    /**
     * 获取当前线程的数据库连接
     */
    public Connection getCurrentConnection() {
        return connectionThreadLocal.get();
    }

    /**
     * 关闭连接并清除ThreadLocal
     */
    public void closeConnection() {
        Connection connection = connectionThreadLocal.get();
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // 处理关闭异常
            } finally {
                connectionThreadLocal.remove();
            }
        }
    }
}
